package freespiritsocial.io.user.ui.fragment.post

import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.data.model.bean.CommentPojo
import freespiritsocial.io.user.databinding.FrgCommentDialogBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.event.EventViewModel
import freespiritsocial.io.user.ext.circleImageUrl
import freespiritsocial.io.user.ext.hideSoftKeyboard
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ui.adapter.PostCommentsAdapter
import freespiritsocial.io.user.ui.fragment.mine.MineFrg
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.PostDetailViewModel
import me.hgj.jetpackmvvm.base.fragment.BaseBottomSheetDialogFragment
import me.hgj.jetpackmvvm.ext.getAppViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

class CommentDialogFragment: BaseBottomSheetDialogFragment() {
    companion object {
        fun crate(mViewModel: PostDetailViewModel,parent: ExplorePostDetailItemFrg) = CommentDialogFragment().apply {
            this.mViewModel = mViewModel
            this.parent = parent
        }
    }

    val eventViewModel: EventViewModel by lazy { getAppViewModel<EventViewModel>() }

    var curCommentId: Long? = null

    private lateinit var mViewModel: PostDetailViewModel
    private lateinit var parent: ExplorePostDetailItemFrg
    private val headerView by lazy(LazyThreadSafetyMode.NONE) {
        TextView(context).apply {
            textSize = 17f
            text = "${mViewModel.data.value?.commentCountStr} ${if (mViewModel.data.value?.commentCount ?: 0 <= 1) "comment" else "comments"}"
            gravity = Gravity.CENTER
            layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        }
    }
    private val commentsAdapter by lazy(LazyThreadSafetyMode.NONE) {
        PostCommentsAdapter(mViewModel).apply {
            goToPeople = {
                goToPeopleHome(it)
            }
            reply = {
                curCommentId = it
                mDatabind.etMessage.isFocusable = true
                mDatabind.etMessage.isFocusableInTouchMode = true
                mDatabind.etMessage.requestFocus()
                val imm: InputMethodManager? = ContextCompat.getSystemService(requireContext(),InputMethodManager::class.java)
                imm?.showSoftInput(mDatabind.etMessage,0)
            }
            loadMoreModule.setOnLoadMoreListener {
                mViewModel.getComments(data.lastOrNull()?.commentId)
            }
            headerWithEmptyEnable = true
        }
    }
    private lateinit var mDatabind: FrgCommentDialogBinding
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        mDatabind = DataBindingUtil.inflate(inflater,R.layout.frg_comment_dialog,container,false)
        mDatabind.lifecycleOwner = this
        return mDatabind.root
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        mDatabind.model = mViewModel
        mDatabind.commentRecycler.init(
            commentsAdapter,
            emptyText = "No one has commented yet, let's write the first comment.",
            emptyImage = R.mipmap.empty_comments
        ).addItemDecoration(SpaceItemDecoration(dp2px(20f),dp2px(20f),firstNeedTop = false))
        commentsAdapter.setHeaderView(headerView)
        mDatabind.commentIvAvatar.circleImageUrl(CacheUtil.getUser()?.userAvatar)
        mDatabind.close.setOnClickListener {
            dismiss()
        }
        CacheUtil.getUser()?.userAvatar?.let { mDatabind.commentIvAvatar.circleImageUrl(it) }
        topOffset = dp2px(200f)
        mViewModel.getComments()

        mDatabind.etMessage.setOnFocusChangeListener { _,hasFocus ->
            mDatabind.flTip.isVisible = !hasFocus
        }

        eventViewModel.keyBoardShowEvent.observe(this) {
            if (it.not()) {
                mDatabind.etMessage.clearFocus()
                curCommentId = null
            }
        }

        mDatabind.tvSend.setOnClickListener {
            send()
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        hideSoftKeyboard(mDatabind.etMessage)
        super.onDismiss(dialog)
    }

    private fun send() {
        hideSoftKeyboard(mDatabind.etMessage)
        mViewModel.comment(curCommentId) {
            mViewModel.commentContent.set("")
            mViewModel.getComments()
        }
    }

    private fun goToPeopleHome(id: String?) {
        mViewModel.getUserInfo(id) {
            dismiss()
            parent.nav().navigateAction(R.id.mineFrg,bundleOf(MineFrg.KEY_IS_USER to false,MineFrg.KEY_USER to it))
        }
    }

    fun setData(list: List<CommentPojo>,isRefresh: Boolean) {
        if (isRefresh)
            commentsAdapter.data.clear()
        commentsAdapter.addData(list)
        commentsAdapter.loadMoreModule.loadMoreComplete()
        commentsAdapter.loadMoreModule.isEnableLoadMore = list.isNotEmpty()
    }
}